package com.yangjun.controller.realtimeLiveAnalysis.realtimeSituation;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.common.ownplatform.Define;
import com.yangjun.common.ownplatform.LineChartID;
import com.yangjun.dao.impl.realtimeLiveAnalysis.realtimeSituation.OwnPlatformImpl;
import com.yangjun.entity.realtimeliveAnalysis.RealTimeOverviewEntity;
import com.yangjun.utils.DvDateUtils;
import com.yangjun.utils.EchartUtils;


/**
 * Created with IntelliJ IDEA.
 * User: xvitcoder
 * Date: 12/20/12
 * Time: 5:27 PM
 */
@Controller
@RequestMapping("/own")
public class OwnPlatformController {
	
	class ChartAttr {
		public String name;
		public String legend;
		
		public ChartAttr(String name, String legend) {
			this.name = name;
			this.legend = legend;
		}
	}
	
    @Autowired
    OwnPlatformImpl mModel;
    
    static {
		
	}
    
    /*
     * Brief: 响应平台类型
     */
    @RequestMapping("/platform")
    @ResponseBody
    public List<Map<String, Object>> getPlatform(HttpServletResponse response, 
    										HttpServletRequest request) {
    	List<Map<String, Object>> resultList = mModel.getPlatform();
    	for(Map<String, Object> resultMap : resultList){
    		String id = resultMap.get("ORDERSOURCE").toString();
    		if("1".equals(id)){
    			//客服代下也算PC网站
    			resultMap.put("ORDERSOURCE", "1,2");
			}
    	}
    	return resultList;
    }
    
    /*
     * Brief: 响应自建平台主页面请求
     */
    @RequestMapping("/overview")
    @ResponseBody
    public Map<String, Object> getOverviewData(HttpServletResponse response, 
    										HttpServletRequest request,
    										@RequestParam(value = "today", required = false) String today,
    										@RequestParam(value = "contrastday", required = false) String contrastday,
    										@RequestParam(value = "platformstr",required = false)String platformstr ) {
    	
    	System.out.println("OwnPlatform overview: Today = " + today + ", contrastday = " + contrastday + ", platformstr = " + platformstr);
    	
    	Map<String, Object> resultMap = Maps.newHashMap();
    	
    	// 参数异常处理
    	if (StringUtils.isBlank(today))
    		today = DvDateUtils.getDate(new Date(), 0);
    	if (StringUtils.isBlank(contrastday))
    		contrastday = DvDateUtils.getDate(new Date(), -7);
    	
    	String yestoday = DvDateUtils.getDate(new Date(), -1);
    	
    	if (org.apache.commons.lang3.StringUtils.isBlank(platformstr))
    		platformstr = Define.OWNPLATFORM_IDS;
    	
    	String[] platformarr = new String[]{};
    	if(StringUtils.isNotBlank(platformstr)){
    		platformarr = platformstr.replace(" ","").split(",");
    	}
    	
    	// 总览
    	List<Map<String, Object>> dataList = mModel.getOverviewData(today,yestoday, contrastday, Arrays.asList(platformarr));
    	resultMap = EchartUtils.resultMap(today, yestoday, contrastday, dataList);
	   	
	   	Float oldVisitCntRatio;
	   	if (dataList.size() <= 1 || dataList.get(1).get("oldVisitCnt") == null || dataList.get(1).get("visitCnt") == null)
	   		oldVisitCntRatio = null;
	   	else
	   		oldVisitCntRatio = Float.parseFloat(dataList.get(1).get("oldVisitCnt").toString()) / Float.parseFloat(dataList.get(1).get("visitCnt").toString());
	   	resultMap.put("oldVisitCntRatio", oldVisitCntRatio);
	   	
	   	Float oldCusAmountRatio;
	   	if (dataList.size() <= 1 || dataList.get(1).get("oldCusAmount") == null || dataList.get(1).get("sale") == null)
	   		oldCusAmountRatio = null;
	   	else
	   		oldCusAmountRatio = Float.parseFloat(dataList.get(1).get("oldCusAmount").toString()) / Float.parseFloat(dataList.get(1).get("sale").toString());
	   	resultMap.put("oldCusAmountRatio", oldCusAmountRatio);
	   	
	   	Float oldOrderCntRatio;
	   	if (dataList.size() <= 1 || dataList.get(1).get("oldOrderCnt") == null || dataList.get(1).get("orderCnt") == null)
	   		oldOrderCntRatio = null;
	   	else
	   		oldOrderCntRatio = Float.parseFloat(dataList.get(1).get("oldOrderCnt").toString()) / Float.parseFloat(dataList.get(1).get("orderCnt").toString());
	   	resultMap.put("oldOrderCntRatio", oldOrderCntRatio);
	   	
	   	Float oldCusCntRatio;
	   	if (dataList.size() <= 1 || dataList.get(1).get("oldCusCnt") == null || dataList.get(1).get("cusCnt") == null)
	   		oldCusCntRatio = null;
	   	else
	   		oldCusCntRatio = Float.parseFloat(dataList.get(1).get("oldCusCnt").toString()) / Float.parseFloat(dataList.get(1).get("cusCnt").toString());
	   	resultMap.put("oldCusCntRatio", oldCusCntRatio);
	   	
	   	// 采购供应
	   	List<Map<String, Object>> stockOutList = mModel.getOutStockWaresSummary(today, contrastday, Arrays.asList(platformarr));
	   	resultMap.put("outstockwares", stockOutList);
	   	
	   	// 退款
	   	List<Map<String, Object>> refundList = mModel.getRefund(today, contrastday, Arrays.asList(platformarr));
	   	resultMap.put("refund", refundList);
	   	
	   	// 物流
	   	List<Map<String, Object>> logisticsList = mModel.getLogistics(today, contrastday, Arrays.asList(platformarr));
	   	resultMap.put("logistics", logisticsList.size() > 0 ? logisticsList.get(0) : null);
	   	 
	   	response.setHeader("Access-Control-Allow-Origin", "*");
	   	return resultMap;
    }
    
    /*
     * 响应所有图表数据
     */
    @RequestMapping(value="/chart", method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object>  getChartData(HttpServletResponse response,
    										@RequestParam(value = "today", required = false) String today,
    										@RequestParam(value = "contrastday", required = false) String contrastday, 
    										@RequestParam(value = "platformstr",required = false)String platformstr ) {
    	
    	System.out.println("OwnPlatform chart: Today = " + today + ", contrastday = " + contrastday + ", platformstr = " + platformstr);
    	
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	String[] indexArr = {"sale", "orderCnt", "visitCnt", "convertRatio", "regCustomerRatio", "payOnDeliveryRatio", "networkConsultCnt", "phoneConsultCnt", "registerCnt", "preOrderCnt", "consignOutCnt", "consignDeliverCnt", "pickCnt", "refundOrderCnt", "refundOrderHandleCnt"};
     	Map<String, Object> resultMap = Maps.newHashMap();
     	
     	// 参数异常处理
    	if (org.apache.commons.lang3.StringUtils.isBlank(today))
    		today = DvDateUtils.getDate(new Date(), 0);
    	if (org.apache.commons.lang3.StringUtils.isBlank(contrastday))
    		contrastday = DvDateUtils.getDate(new Date(), -7);
    	if (org.apache.commons.lang3.StringUtils.isBlank(platformstr))
    		platformstr = Define.OWNPLATFORM_IDS;
    	
    	String[] platformarr = new String[]{};
    	if (StringUtils.isNotBlank(platformstr)) {
    		platformarr = platformstr.replace(" ","").split(",");
    	}
     	
     	// Line chart
     	for (String index : indexArr) {
        	resultMap.put(index, getLineChartMap(index, today, contrastday, Arrays.asList(platformarr)));
     	}
     	
     	// Bar chart
     	resultMap.put("SalesAmountByPlatform", getBarChartMap(new ChartAttr("销售额", "销售额"), today, Arrays.asList(platformarr)));
     	resultMap.put("VisitCntByPlatform", getBarChartMap(new ChartAttr("访客数", "访客数"), today, Arrays.asList(platformarr)));
     	
     	// Pie chart
     	resultMap.put("SalesProportionByPlatform", getPieChartMap(new ChartAttr("销售额", "销售额"), today, Arrays.asList(platformarr)));
     	resultMap.put("OutstockOrderAmt", getPieChartMap(new ChartAttr("缺货销售额", "缺货销售额"), today, Arrays.asList(platformarr)));
     	
        return resultMap;
    }
    
    /*
     * 响应某个渠道转化率
     */
    @RequestMapping(value="/channelconvertratio", method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getChannelVisitCnt(HttpServletResponse response, 
    											@RequestParam(value = "channel", required = false) String channel) {
    	
    	Map<String, Object> resultMap = Maps.newHashMap();
    	
    	return resultMap;
    }
    
    @SuppressWarnings("unused")
	public Map<String,Object> getLineChartMap(String identification, String today, String contrastday, List<String> ordersources) {
        String[] todayHourDataArr = new String[24];
        String[] contrastdayHourDataArr = new String[24];
        Map<String,Object> itemMap = Maps.newHashMap();
        List<Map<String,Object>> querylist = null;
        int index = 0;
        if ("sale".equals(identification)) {
            querylist = mModel.getLineChartData(LineChartID.sale, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_SALE);
        } else if("orderCnt".equals(identification)) {
            querylist = mModel.getLineChartData(LineChartID.OrderCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_ORDERCNT);
        } else if("visitCnt".equals(identification)) {
            querylist = mModel.getLineChartData(LineChartID.VisitCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_VISITCNT);
        } else if("convertRatio".equals(identification)) {
            querylist = mModel.getLineChartData(LineChartID.ConvertRatio, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_CONVERTRATIO);
        } else if("regCustomerRatio".equals(identification)) {
            querylist = mModel.getLineChartData(LineChartID.RegCustomerRatio, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_REQCUSTOMERRATIO);
        } else if("payOnDeliveryRatio".equals(identification)) {
            querylist = mModel.getLineChartData(LineChartID.PayOnDeliveryRatio, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_PayOnDeliveryRatio);
        } else if("networkConsultCnt".equals(identification)) {
            querylist = mModel.getLineChartData(LineChartID.NetworkConsultCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_NETWORKCONSULTCNT);
        } else if("phoneConsultCnt".equals(identification)) {
            querylist = mModel.getLineChartData(LineChartID.PhoneConsultCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_PHONECONSULTCNT);
        } else if ("registerCnt".equals(identification)) {
        	querylist = mModel.getLineChartData(LineChartID.RegisterCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_REGISTERCNT);
        } else if ("preOrderCnt".equals(identification)) {
        	querylist = mModel.getLineChartData(LineChartID.PreOrderCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_PREORDERCNT);
        } else if ("consignOutCnt".equals(identification)) {
        	querylist = mModel.getLineChartData(LineChartID.ConsignOutCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_CONSIGOUTCNT);
        } else if ("consignDeliverCnt".equals(identification)) {
        	querylist = mModel.getLineChartData(LineChartID.ConsignDeliverCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_CONSIGNDELIVERCNT);
        } else if ("pickCnt".equals(identification)) {
        	querylist = mModel.getLineChartData(LineChartID.PickCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_PICKCNT);
        } else if ("refundOrderCnt".equals(identification)) {
        	querylist = mModel.getLineChartData(LineChartID.RefundOrderCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_REFUNDORDERCNT);
		} else if ("refundOrderHandleCnt".equals(identification)) {
			querylist = mModel.getLineChartData(LineChartID.RefundOrderHandleCnt, today, contrastday, ordersources);
            itemMap.put("name",DVConstants.OWNPLATFORM_CHART_NAME_REFUNDORDERHANDLECNT);
		} 
        
        if (querylist == null)
        	System.out.println("Error: identification = " + identification);
        
        for(Map<String,Object> map : querylist){
            String day = String.valueOf(map.get("dataDate"));
            String hour = String.valueOf(map.get("dataHour"));
            if(hour.startsWith("0")){
            	if(day.equals(today)){
            		index = Integer.valueOf(hour);
                	todayHourDataArr[Integer.parseInt(hour.substring(1))] =String.valueOf(map.get(identification));
            	}else{
            		contrastdayHourDataArr[Integer.parseInt(hour.substring(1))] =String.valueOf(map.get(identification));
            	}
            }else{
            	if(day.equals(today)){
            		index = Integer.valueOf(hour);
                	todayHourDataArr[Integer.parseInt(hour)] =String.valueOf(map.get(identification));
            	}else{
            		contrastdayHourDataArr[Integer.parseInt(hour)] =String.valueOf(map.get(identification));
            	}
            }
        }
        
        itemMap.put("legend",DVConstants.REALTIME_CHART_LEGEND);
        itemMap.put("xAxis", DVConstants.TWENTY_FOUR_HOURS_XAXIS);
        itemMap.put("today", todayHourDataArr);
        itemMap.put("contrastday", contrastdayHourDataArr);
        return itemMap;
    }
    
    /*
     * Brief：响应柱状图数据
     */
    public Map<String, Object> getBarChartMap(ChartAttr chartAttr, String today, List<String> orderSources) {
    	Map<String, Object> barDataMap;
    	
    	if (chartAttr.name == "销售额") {
    		barDataMap = mModel.getSalesAmount(today, orderSources);
        	barDataMap.put("name", chartAttr.name);
        	barDataMap.put("legend", chartAttr.legend);
    	} else if (chartAttr.name == "访客数") { 
    		barDataMap = mModel.getChannelVisitCnt(today);
        	barDataMap.put("name", chartAttr.name);
        	barDataMap.put("legend", chartAttr.legend);
    	}else {
    		barDataMap = null;
    	}
    	
    	return barDataMap;
    }
    
    /*
     * Brief：响应饼状图数据
     */
    public Map<String, Object> getPieChartMap(ChartAttr chartAttr, String date, List<String> orderSources) {
    	Map<String, Object> barDataMap;
    	
    	if (chartAttr.name == "销售额") {
    		barDataMap = mModel.getSaleProportion(date, orderSources);
        	barDataMap.put("name", "销售额占比");
    	} else if (chartAttr.name == "缺货销售额") {
    		barDataMap = mModel.getOutStockTotalAmt(date, orderSources);
        	barDataMap.put("name", "采购员影响销售额");
    	} else {
    		barDataMap = null;
    	}
    	
    	return barDataMap;
    }
}













